package top.dyzmj.detty.core.utils.concurrent;

import top.dyzmj.detty.core.utils.internal.InternalThreadLocalMap;

/**
 * 描述: 提供快速访问FastThreadLocal变量的特殊线程。
 *
 * @author dongYu
 * @date 2021/11/24
 */
public class FastThreadLocalThread extends Thread {

	/**
	 * 如果我们有机会包装Runnable，它将被设置为true。
	 */
	private final boolean cleanupFastThreadLocals;

	private InternalThreadLocalMap threadLocalMap;

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread() {
		cleanupFastThreadLocals = false;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(Runnable target) {
		super(FastThreadLocalRunnable.wrap(target));
		cleanupFastThreadLocals = true;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(ThreadGroup group, Runnable target) {
		super(group, FastThreadLocalRunnable.wrap(target));
		cleanupFastThreadLocals = true;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(String name) {
		super(name);
		cleanupFastThreadLocals = false;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(ThreadGroup group, String name) {
		super(group, name);
		cleanupFastThreadLocals = false;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(Runnable target, String name) {
		super(FastThreadLocalRunnable.wrap(target), name);
		cleanupFastThreadLocals = true;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(ThreadGroup group, Runnable target, String name) {
		super(group, FastThreadLocalRunnable.wrap(target), name);
		cleanupFastThreadLocals = true;
	}

	/**
	 * 构造对象
	 */
	public FastThreadLocalThread(ThreadGroup group, Runnable target, String name, long stackSize) {
		super(group, FastThreadLocalRunnable.wrap(target), name, stackSize);
		cleanupFastThreadLocals = true;
	}

	/**
	 * 如果FastThreadLocal.removeAll()在Thread.run()完成后被调用，则返回true
	 */
	public static boolean willCleanupFastThreadLocals(Thread thread) {
		return thread instanceof FastThreadLocalThread &&
				((FastThreadLocalThread) thread).willCleanupFastThreadLocals();
	}

	/**
	 * 返回保持线程局部变量绑定到该线程的内部数据结构。
	 * 请注意，此方法仅供内部使用，因此可以随时更改。
	 */
	public final InternalThreadLocalMap threadLocalMap() {
		return threadLocalMap;
	}

	/**
	 * 设置保持线程局部变量绑定到该线程的内部数据结构。
	 * 请注意，此方法仅供内部使用，因此可以随时更改。
	 */
	public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) {
		this.threadLocalMap = threadLocalMap;
	}

	/**
	 * 如果FastThreadLocal.removeAll()在run()完成后被调用，则返回true。
	 */
	public boolean willCleanupFastThreadLocals() {
		return cleanupFastThreadLocals;
	}

}
